package com.zchat.android;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;

import com.zchat.android.app.BaseActivity;
import com.zchat.android.preferences.Preferences;
import com.zchat.android.service_aidl_beans.User;
import com.zchat.api.log.Logger;
import com.zchat.api.modules.ModuleManager;
import com.zchat.api.modules.system.SystemModule;
import com.zchat.api.util.Helpers;
import com.zchat.api.util.Resolution;

/**
 * 
 * @author Oliverzhu
 * 2012/6/15
 */
public class BootActivity extends BaseActivity {
	private static final String TAG = "BootActivity";
	/** 网络监测 */
	private static boolean detected = false;
	
	private LinearLayout layout;
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.boot);
        super.onCreate(savedInstanceState);
        
        Resolution.getInstance().setScreenWidth(getWindowManager().getDefaultDisplay().getWidth());
		Resolution.getInstance().setScreenHeight(getWindowManager().getDefaultDisplay().getHeight());
		
		//加载默认启动页
		try {
			InputStream in = getResources().getAssets().open("boot.png");
			SoftReference<Drawable> drawable = new SoftReference<Drawable>(new BitmapDrawable(in));
			layout.setBackgroundDrawable(drawable.get());
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//
		if(Preferences.getAcceptStatus(mPrefs))
		{
			new BootTask().execute();
		}else
		{
			//show protocol
			DialogInterface.OnClickListener accept = new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					//update the preferences and do boot task
					Preferences.setAcceptStatus(mPrefs, "yes");
					
			    	Helpers.showDialog(BootActivity.this, 
			    			"提示", "生成快捷方式到桌面？", 
			    			new int[]{R.string.sure, R.string.cancel}, 
			    			new OnClickListener[]
			    			{
					    		new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										//install shortcut
										Helpers.installShortCut(BootActivity.this);
		//								Toast.makeText(context, R.string.shortCut, 1000).show();
										//系统启动引导任务
										new BootTask().execute();
									}
								},new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										//系统启动引导任务
										new BootTask().execute();
									}
								}
							}
			    	); 	
				}
				
			};
			DialogInterface.OnClickListener exit = new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					//exit the application
					System.exit(0);
				}
				
			};
			Helpers.showDialog(this, 
					R.string.protocol_title, R.string.protocol, 
					new int[]{R.string.accept, R.string.exit},
					new DialogInterface.OnClickListener[]{accept, exit});
		}
    }
    
    /**
	 * Set the application is detecting the net work, if detecting, the main thread will sleep.
	 * @param detected
	 */
	public static void setDetected(boolean result) {
		detected = result;
	}

	@Override
	protected void initComponents() {
		layout = (LinearLayout) findViewById(R.id.boot);
	}

	@Override
	protected void initDatas() {
		
	}

	@Override
	protected void setComponentListeners() {
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(DEBUG) Logger.debug(TAG+"-onResume()");
	}
	
	/**
	 * 启动界面异步任务
	 * @author MichaelHuang
	 *
	 */
	private class BootTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... str) {
			//启动模块管理
			try {
				while(true) {
					if(detected) {
						if(DEBUG) Logger.info(TAG+"-已完成网络检测。");
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
//				Logger.error("启动模块管理产生错误。");
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(zchat.getModuleManager() == null) {
				if(DEBUG) Logger.warn(TAG+"-模块管理加载失败，退出应用");
				//模块管理加载失败，退出应用
				DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						System.exit(0);
					}
					
				};
				Helpers.showDialog(BootActivity.this,
						R.string.tip, R.string.launcherError, 
						new int[]{R.string.sure}, 
						new DialogInterface.OnClickListener[]{listener2});
			} else {
				//模块管理加载成功，开始系统验证
				ModuleManager moduleManager = zchat.getModuleManager();
				SystemModule systemModule = (SystemModule) moduleManager.getModule(SystemModule.class);
				if(systemModule != null) {
					//验证是否存在SD卡
					if(!systemModule.isSDCardMounted()) {
						if(DEBUG) Logger.warn(TAG+"-SD卡没有挂载");
						DialogInterface.OnClickListener listener3 = new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.exit(0);
							}
							
						};
						Helpers.showDialog(BootActivity.this,
								R.string.tip, R.string.mediaMountError, 
								new int[]{R.string.sure}, 
								new DialogInterface.OnClickListener[]{listener3});
						return;
					}
					//SD当前剩余空间是否满足系统要求
					long freeSize = systemModule.freeSize();
					if(freeSize < 5*1024*1024) {
						if(DEBUG) Logger.warn(TAG+"-SD卡剩余空间不足");
						DialogInterface.OnClickListener listener4 = new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.exit(0);
							}
							
						};
						Helpers.showDialog(BootActivity.this,
								R.string.tip, R.string.mediaIdleError, 
								new int[]{R.string.sure}, 
								new DialogInterface.OnClickListener[]{listener4});
						return;
					}
					//在SD卡中创建应用所需文件夹
					try {
						if(!systemModule.createFS()) {
							DialogInterface.OnClickListener listener5 = new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int which) {
									finish();
									System.exit(0);
								}
								
							};
							Helpers.showDialog(BootActivity.this,
									R.string.tip, R.string.createFolderError, 
									new int[]{R.string.sure}, 
									new DialogInterface.OnClickListener[]{listener5});
							return;
						}
					} catch (Exception e1) {
						e1.printStackTrace();
						if(DEBUG) Logger.warn(TAG+"-文件夹创建失败");
					}
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					//Verify if it needed help
					User user = Preferences.getUserNameAndPassword(mPrefs);
					String userName = user.getUserName();
					String userPassword = user.getPassword();
					
					if(userName != null 
							&& userPassword != null 
							&& zchat.isAuthenticated(userName, userPassword))
					{
						//Go to welcome activity
						Intent welcome = new Intent(BootActivity.this, WelcomeActivity.class);
						startActivity(welcome);
						finish();
					}else
					{
						Intent help = new Intent(BootActivity.this, HelpActivity.class);
						startActivity(help);
						finish();
					}
				}
			}
		}
	}
	
	@Override
	public String toString() {
		return TAG;
	}
}